import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:just_audio/just_audio.dart';
import 'package:ride_rex/person_detail/person_detail_logic.dart';
import 'package:ride_rex/service/config_service.dart';
import 'package:ride_rex/sqlite/db_manager.dart';
import 'package:ride_rex/voice_record/voice_record.dart';
import 'package:ylm_ui_kit/ylm_ui_kit.dart';

import '../../constant.dart';
import '../../main/discover/discover_bean.dart';
import '../comment.dart';

class ArticleDetailLogic extends GetxController {
  ArticleDetailLogic(this.bean, this.workBean);

  final FeedUserBean bean;
  final FeedUserWorkBean workBean;

  final TextEditingController commentController = TextEditingController();

  ///切换语音和文本输入
  bool showInput = true;

  int bannerCurrentIndex = 0;

  ///评论列表
  List<CommentBean> commentList = [];

  ///音频播放器
  final AudioPlayer player = AudioPlayer();

  ///正在播放的音频文件名
  String currentAudioFileName = '';

  final ScrollController scrollController = ScrollController();

  bool isTranslating = false;

  String translateTitle = '';
  String translateDescription = '';
  bool showTranslate = false;

  @override
  void onReady() async {
    super.onReady();
    CommonObservable().addObserver(CommonLogic.keyListenerFollow, follow);
    CommonObservable().addObserver(CommonLogic.keyListenerUnfollow, unfollow);
    CommonObservable().addObserver(CommonLogic.keyListenerArticleLike, like);
    CommonObservable().addObserver(CommonLogic.keyListenerArticleCancelLike, cancelLike);
    _getCommentList();

    player.playerStateStream.listen((state) {
      if (state.processingState == ProcessingState.completed) {
        currentAudioFileName = '';
        for (var element in commentList) {
          element.isPlaying = false;
        }
        update();
      }
    });

    ///自动翻译
    Future.delayed(const Duration(milliseconds: 500), () {
      bool autoTranslate = CommonStorage().getBool(StorageKey.spKeyAutoTranslate, defaultValue: false);
      if (autoTranslate) translate();
    });
  }

  void translate() async {
    if (isTranslating) return;
    if (workBean.title.empty && workBean.description.empty) return;

    ///显示Loading
    isTranslating = true;
    update();

    ///翻译
    await Future.wait([
      CommonConfigService.instance.translate(text: workBean.title ?? ''),
      CommonConfigService.instance.translate(text: workBean.description ?? ''),
    ]).then((value) {
      isTranslating = false;
      translateTitle = value[0];
      translateDescription = value[1];
      showTranslate = true;
      update();
    }).whenComplete(() {
      isTranslating = false;
      update();
    });
  }

  void _getCommentList() async {
    if (workBean.workId.empty) return;
    commentList = await DbManager.getCommentList(workId: workBean.workId!);
    update();
  }

  ///发送文本评论
  void sendTextComment() async {
    if (workBean.workId.empty) return;
    if (Loading.predicate(() => commentController.text.empty, 'Please enter your ideas')) return;
    CommentBean bean = CommentBean.text(text: commentController.text);
    await DbManager.addComment(bean: bean, workId: workBean.workId!);
    commentList.add(bean);
    update();
    commentController.clear();
    CommonOperate.hideKeyboard();
    Future.delayed(const Duration(milliseconds: 500), () {
      scrollToBottom();
    });
  }

  ///发送语音评论
  void sendAudioComment({
    required String path,
    required String fileName,
    required int duration,
    required int size,
  }) async {
    if (workBean.workId.empty || path.empty || fileName.empty) return;
    CommentBean bean = CommentBean.audio(
      audioFileName: fileName,
      audioSize: size,
      audioDuration: duration,
    );
    await DbManager.addComment(bean: bean, workId: workBean.workId!);
    commentList.add(bean);
    update();

    scrollToBottom();
  }

  void scrollToBottom() {
    CommonOperate.nextFrameRefresh(() {
      if (scrollController.positions.isEmpty) return;
      scrollController.animateTo(
        scrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 200),
        curve: Curves.easeInOut,
      );
    });
  }

  void playAudio(CommentBean bean) async {
    String fileName = bean.audioFileName ?? '';
    String directory = await VoiceRecord.directory;
    String path = '$directory/$fileName';
    bool exist = await File(path).exists();
    if (Loading.predicate(() => !exist, 'Audio not exist')) return;
    if (player.playing) await player.stop();
    for (var element in commentList) {
      if (element.recordId.equals(bean.recordId)) continue;
      element.isPlaying = false;
    }
    bean.isPlaying = !bean.isPlaying;
    update();
    if (currentAudioFileName.equals(fileName)) {
      currentAudioFileName = '';
      return;
    }
    await player.setFilePath(path);
    player.play();

    currentAudioFileName = fileName;
  }

  void follow(key, [value]) {
    bean.isFriend = true;
    update();
  }

  void unfollow(key, [value]) {
    bean.isFriend = false;
    update();
  }

  void like(key, [value]) {
    String workId = value ?? '';
    if (workId.equals(workBean.workId)) {
      workBean.isLike = '1';
      update();
    }

    for (CommentBean bean in commentList) {
      if (bean.recordId.equals(workId)) {
        bean.isLike = '1';
        update();
        break;
      }
    }
  }

  void cancelLike(key, [value]) {
    String workId = value ?? '';
    if (workId.equals(workBean.workId)) {
      workBean.isLike = '0';
      update();
    }

    for (CommentBean bean in commentList) {
      if (bean.recordId.equals(workId)) {
        bean.isLike = '0';
        update();
        break;
      }
    }
  }

  void onPageChanged(int index, _) {
    bannerCurrentIndex = index;
    update();
  }

  void changeInput() {
    showInput = !showInput;
    update();
  }

  @override
  void onClose() {
    commentController.dispose();
    player.dispose();
    CommonObservable().removeObserver(CommonLogic.keyListenerFollow, follow);
    CommonObservable().removeObserver(CommonLogic.keyListenerUnfollow, unfollow);
    CommonObservable().removeObserver(CommonLogic.keyListenerArticleLike, like);
    CommonObservable().removeObserver(CommonLogic.keyListenerArticleCancelLike, cancelLike);
    super.onClose();
  }
}
